<template>
  <div class="index-container">
    <div class="main-header">
      <el-row>
        <el-col v-if="type === 9" :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-button
            type="primary"
            icon="el-icon-plus"
            class="sureBtn"
            size="medium"
            @click="handleAdd"
          >
            新增角色
          </el-button>
        </el-col>
      </el-row>
    </div>
    <div class="main-content">
      <app-table
        :page-data="pageDataList"
        :table-columns="tableColumns"
        @current-change="handleCurrentChange"
        @handleCheckedRows="handleCheckedRows"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            @click="editRow(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="success"
            @click="delRow(scope.row)"
          >
            删除
          </el-button>
        </template>
      </app-table>
    </div>
    <el-dialog
      width="50%"
      :title="title"
      :visible.sync="dialogVisible"
      :before-close="closeDialog"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
              <el-form-item label="归属部门" prop="departType">
                <el-select
                  v-model="form.departType"
                  size="medium"
                  clearable
                  placeholder="请选择部门归属"
                  filterable
                  style="width: 100%;"
                  @change="handleDepartType"
                >
                  <el-option :key="0" label="行政部" :value="1"></el-option>
                  <el-option :key="1" label="业务部" :value="2"></el-option>
                  <el-option :key="2" label="运营中心" :value="3"></el-option>
                  <el-option :key="3" label="护理部" :value="4"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="部门名称" prop="branch_id">
              <el-select v-model="form.branch_id" placeholder="请选择部门名称" style="width: 100%;">
                <el-option v-for="item in dataList" :key="item.id" :label="item.name" :value="item.id" ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="角色备注" prop="content">
              <el-input v-model="form.content" type="textarea" placeholder="请输入角色备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="设置权限">

            </el-form-item>
          </el-col>
        </el-row>
        <el-card class="form-container" shadow="never">
          <div v-for="(cate,index) in asyncRoutes" :key="'cate'+index" :class="index===0?'top-line':null">
            <el-row v-if="!cate.hide" class="table-layout" style="background: #F2F6FC;">
              <el-checkbox v-model="cate.checked"
                          :indeterminate="false"
                          @change="(e)=>handleCheckAllChange(e, cate)">
                {{ cate.meta && cate.meta.title }}
              </el-checkbox>
            </el-row>
            <el-row v-if="!cate.hide" class="table-layout">
              <el-col v-for="(resource, idx) in cate.children" :key="'resource'+idx" :span="8" style="padding: 4px 0">
                <el-checkbox v-if="!(resource.meta && resource.meta.hidden)" v-model="resource.checked" @change="(e) => handleCheckChange(e, resource, cate)">
                  {{ resource.meta && resource.meta.title }}
                </el-checkbox>
              </el-col>
            </el-row>
          </div>
          <div style="margin-top: 20px" align="center">
            <el-button type="primary" @click="handleSave">提交</el-button>
            <el-button @click="handleClear">取消</el-button>
          </div>
        </el-card>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
  import appTable from "@/components/AppTable/index";
  import { getList } from "@/api/nursemanager";
  import { mapGetters } from "vuex";
  import { asyncRoutes } from "@/router";
  import { getbranchtree, getrole, getroleinfo, branchsearch } from "@/api/depart";
  export default {
    name: "Role",
    components: { appTable },
    data() {
      return {
        currentSelectedData: [],
        pageDataList: {
          type: -1
        },
        selectForm: {
          page_size: 20
        },
        tableColumns: [
          { prop: "name", label: "角色名称", width: '180px' },
          { prop: "branch_name", label: "所属部门", width: '220px' },
          { prop: "content", label: "职位职责" },
          { prop: "update_time", label: "最后修改时间", formatter: this.timeformatter, width: '180px' },
          { prop: "create_time", label: "添加时间", width: '180px' },
        ],
        //角色添加
        title: "新增角色",
        dataList: [],
        dialogVisible: false,
        asyncRoutes: asyncRoutes,
        form: {
          name: "",
          branch_id: "",
          content: "",
          permis: []
        },
        rules: {
          name: [
            { required: true, message: '请输入角色名称', trigger: 'blur' },
          ],
          branch_id: [
            { required: true, message: '请选择所属部门', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '请选择角色备注', trigger: 'blur' },
          ]
        }
      };
    },
    computed: {
      ...mapGetters({
        avatar: "user/avatar",
        username: "user/username",
        name: "user/name",
        type: "user/type",
      }),
    },
    created() {},
    beforeDestroy() {},
    mounted() {
      this.getTableData();
      // console.log('asyncRoutes', asyncRoutes)
      // getbranchtree("get").then((resp) => {
      //   if (resp.code === 200) {
      //     this.dataList = resp.data;
      //   }
      // });
    },
    methods: {
      handleDepartType(value) {
        branchsearch({type: value}).then(res => {
          this.dataList = res.data;
          if(res.data.length == 0) {
            this.$set(this.form, "branch_id", "")
          } else {
            this.$set(this.form, "branch_id", res.data[0].id)
          }
        })
      },
      timeformatter(row) {
        if(row.update_time) {
          return row.update_time
        } else {
          return row.create_time
        }
      },
      handleCheckAllChange(value, cate) {
        cate.checked = value;
        if(!Array.isArray(this.form.permis)) {
          this.$set(this.form, "permis", [])
        }
        if(value) {
          if(!this.form.permis.includes(cate.id)) {
            this.form.permis.push(cate.id)
          }
          cate.children.map(item => {
            if(!this.form.permis.includes(item.id)) {
              this.form.permis.push(item.id)
            }
          })
        } else {
          let permis = this.form.permis.filter(item => item != cate.id)
          cate.children.map(item => {
            permis = permis.filter(ite => ite != item.id)
          })
          this.$set(this.form, "permis", permis)
        }
        cate.children.map((item, index) => {
          item.checked = value;
          value && this.form.permis.push(item.id)
        })
        this.$forceUpdate();
      },
      handleCheckChange(value, resource, cate) {
        resource.checked = value;
        if(!Array.isArray(this.form.permis)) {
          this.$set(this.form, "permis", [])
        }
        if(value) {
          if(!this.form.permis.includes(resource.id)) {
            this.form.permis.push(resource.id)
          }
        } else {
          let permis = this.form.permis.filter(item => item != resource.id)
          this.$set(this.form, "permis", permis)
        }
        let count = 0;
        cate.children.map(item => {
          if(item.checked){
            count++
          }
        })
        if(count == cate.children.length) {
          cate.checked = true;
        } else {
          cate.checked = false;
        }
        this.$forceUpdate();
      },
      editRow(row) {
        let permis = !Array.isArray(row.permis) && row.permis.split(",").map(Number) || row.permis
        this.title = "编辑角色";
        this.dialogVisible = true;
        this.form = {...row, permis}
        this.asyncRoutes && this.asyncRoutes.length > 0 && this.asyncRoutes.forEach(item => {
          if(permis.includes(item.id)) {
            item.checked = true;
          } else {
            item.checked = false;
          }
          item.children && item.children.length > 0 && item.children.forEach(ite => {
            if(permis.includes(ite.id)) {
              ite.checked = true;
            } else {
              ite.checked = false;
            }
          })
        })
        this.$forceUpdate();
        console.log(this.asyncRoutes)
      },
      delRow(row) {
        this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              getrole("delete", {
                id: row.id,
              }).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getTableData();
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
      },
      typeFormatter(row) {
        if (row.type == 9) {
          return "管理员";
        } else if (row.type == 1) {
          return "员工";
        } else if (row.type == 2) {
          return "护工";
        }
      },
      getTableData() {
        let data = this.selectForm;
        getrole("get", data).then((resp) => {
          if (resp.code === 200) {
            this.pageDataList = Object.assign(resp.data, {type: -1})
          }
        });
      },
      handleAdd() {
        this.title = "新增角色";
        this.asyncRoutes && this.asyncRoutes.length > 0 && this.asyncRoutes.map(item => {
          item.checked = false;
          item.children && item.children.length > 0 && item.children.map(ite => {
            ite.checked = false;
          })
        })
        this.dialogVisible = true;
        // this.key = Math.random();
      },
      handleClear() {
        this.dialogVisible = false;
        this.form = {};
        this.$refs["form"].resetFields();
      },
      closeDialog() {
        this.dialogVisible = false;
        this.$refs["form"].resetFields();
        this.form = {};
      },
      handleSave() {
        Object.assign(this.form, {permis: `${Array.isArray(this.form.permis) && this.form.permis || '[]'}`})
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            if (this.form.id) {
              getrole("put", this.form).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "修改成功",
                  });
                  this.getTableData();
                  this.handleClear();
                }
              });
            } else {
              getrole("post", this.form).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "添加成功",
                  });
                  this.getTableData();
                  this.handleClear();
                } else {
                  this.$message({
                    type: "error",
                    message: resp.msg,
                  });
                }
              });
            }
          }
        });
      },
      handleCheck() {
        if (this.currentSelectedData.length === 0) {
          this.$message({
            message: "请选择一条您要查看的内容",
            type: "warning",
          });
        } else if (this.currentSelectedData.length > 1) {
          this.$message({
            message: "一次只能查看一条内容",
            type: "warning",
          });
        } else {
        }
      },
      handleDelete() {
        if (this.currentSelectedData.length === 0) {
          this.$message({
            message: "请选择一条您要删除的内容",
            type: "warning",
          });
        } else if (this.currentSelectedData.length > 1) {
          this.$message({
            message: "一次只能删除一条内容",
            type: "warning",
          });
        } else {
          this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.ruleForm = Object.assign({}, this.currentSelectedData[0]);
              let param = {
                id: this.ruleForm.id,
              };
              getList("delete", param).then((resp) => {
                if (resp.code === 200) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getTableData();
                }
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        }
      },
      handleCheckedRows(rows) {
        if (rows && rows instanceof Array && rows.length > 0) {
          this.currentSelectedData = rows;
        } else {
          this.currentSelectedData = [];
        }
      },
      handleCurrentChange(val) {
        this.selectForm.page = val;
        this.getTableData();
      },
      search() {
        this.selectForm.page = 1;
        this.getTableData();
      },
    },
  };
</script>
<style lang="scss" scoped>
.table-layout {
    padding: 20px;
    border-left: 1px solid #DCDFE6;
    border-right: 1px solid #DCDFE6;
    border-bottom: 1px solid #DCDFE6;
  }

  .top-line {
    border-top: 1px solid #DCDFE6;
  }
  .index-container {
    box-sizing: border-box;
    width: 100%;
    padding: 0 30px !important;
    margin: 0 !important;
    background: #fff !important;

    .main-header {
      padding-top: 4px;
      margin-bottom: 24px;

      .search {
        width: 100%;

        .search-title {
          flex: 0 0 48px;
          width: 48px;
          font-size: 16px;
          line-height: 36px;
          color: #333;
        }
      }
    }

    .form-footer {
      padding-left: 100px;
    }
  }
</style>
